<!-- 创建工单组件 -->
<template>
	<view style="width: 100%;padding: 20rpx;box-sizing: border-box;background-color: #fff;height:100%">
		<!-- 自定义头部组件 -->
		<HeaderTitle :title="title" :isBack="true" :isSearch="false" />
		<div>
			<uni-forms ref="form" :modelValue="entity" label-width="100px">
				<div>
					<uni-forms-item label="客户名称：" :rules="$rules.handle.CustomerName" required name="CustomerName">
						<view @click="CustomerChoice">
							<uni-easyinput v-model="entity.CustomerName" placeholder="请选择客户" suffixIcon="compose"
								:disabled="true" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="工单类型：" :rules="$rules.handle.SWOType" required name="SWOType">
						<view>
							<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
								v-model="entity.SWOType" :localdata="SWOTypeOptions" @change="SWOTypeOptionsChange"
								:disabled="disabled"></uni-data-select>
						</view>
					</uni-forms-item>
					<uni-forms-item v-if="SWOTypeName === '样品服务'" label="关联单号:" :rules="$rules.handle.RelationNo"
						required name="RelationNo">
						<view @click="sampleChoice">
							<uni-easyinput v-model="entity.RelationNo" placeholder="关联单号" :disabled="disabled" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="工单标题：" :rules="$rules.handle.SWOTitle" required name="SWOTitle">
						<view>
							<uni-easyinput v-model="entity.SWOTitle" placeholder="工单标题" :disabled="disabled" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="开始日期：">
						<view @click="timeClick('StartTime')">
							<uni-easyinput v-model=" entity.StartTime" placeholder="请选择开始日期" :disabled="true" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="完成日期：">
						<view @click="timeClick('EndTimeRqstd')">
							<uni-easyinput v-model=" entity.EndTimeRqstd" placeholder="请选择完成日期" :disabled="true" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="执行人：" :rules="$rules.handle.SalesmanName" required name="SalesmanName">
						<view @click="SalesmanNameClick(entity.SalesmanName)">
							<uni-easyinput v-model="entity.SalesmanName" placeholder="执行人" :disabled="disabled"
								@clear="$refs['form'].clearValidate('SalesmanName')" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="工单内容：">
						<view>
							<uni-easyinput v-model="entity.SWOContent" placeholder="工单内容" type="textarea"
								maxlength="300" :disabled="disabled" />
						</view>
					</uni-forms-item>
				</div>
				<div v-if="!disabled">
					<div class="submitButton">
						<u-button type="primary" style="font-size: 14px;margin-top: 20rpx;" @click="onSubmit"
							:loading="loading">提交</u-button>
					</div>
				</div>
			</uni-forms>

			<!-- 经办人下拉列表数据 -->
			<!-- <u-picker mode="selector" v-model="isShowPickerRealName" :default-selector="[0]" :range="selectorObjRealName"
				:range-key="rangeKeyRealName" @confirm="showPickerChangeRealName"></u-picker> -->

			<Myuser @customerChoice="Client" ref="myuser" />

			<!-- 关联单号组件 -->
			<Sample @sampleClickChange="ClientSample" ref="Sample" />
			<!-- 执行人弹出层 -->
			<UniPopup ref="UniPopup" @confrim="UniPopupConfrim" />
			<!-- 选择日期 -->
			<u-calendar v-model="isCalendar" :mode="mode" placeholder="请选择日期" @change="timeChangeClick"
				max-date="2026-01-01"></u-calendar>
		</div>
	</view>

</template>

<script>
	import {
		Base_DictionaryMainGetTheDataByDicKey,
		Base_ManageBase_UserGetDataList,
		ServiceWorkOrderMainSaveData,
		ServiceWorkOrderMainUpdateData,
		ServiceWorkOrderMainGetTheDataForDetail
	} from '@/api/interface.js'

	// 引入关联单号组件
	import Sample from "../../components/sample.vue";
	//客户
	import Myuser from "../../components/OwnUser.vue";
	import UniPopup from "../../components/UniPopup.vue";
	// 引入顶部navbar组件
	import HeaderTitle from '@/components/header/header-title.vue'
	export default {
		props: {
			parentObj: Object
		},
		components: {
			UniPopup,
			Myuser,
			Sample,
			HeaderTitle
		},
		data() {
			return {

				dateType: "",
				rangeKeyRealName: "RealName",
				isShowPickerRealName: false, //是否展示执行人人下拉列表
				selectorObjRealName: [], //执行人下拉列表数据
				// 用来判断关联单号
				SWOTypeName: "",
				// 工单类型下拉列表
				SWOTypeOptions: [],
				// 是否显示日期弹窗
				isCalendar: false,
				// 日期选择
				mode: 'date',
				// 按钮是否禁用
				disabled: false,
				// 导航栏标题  0新增 1修改
				title: "",
				loading: false,
				info: {},
				SWOAList: [],
				showUser: false,
				entity: {},
				data: [],
				showPicker: false,
				show: false,
				showDate: false,
				Id: "",
				EndshowDate: false,
				columns: [],
				// 从工单管理页面 1  跳转的还是我的工单页面 0跳转的
				urlType: 1,
				options: {},
				title: ""
			};
		},
		onShow() {
			//默认赋值当前选择日期
			let time = this.$moment().format("YYYY-MM-DD");
			this.entity.StartTime = time
			// this.openForm(obj);
		},
		onLoad(options) {

			this.options = options
			console.log('工单过来了', this.options)
			this.title = options.title + '工单'
			if (options.title === '新建') {
				// 获取工单类型下拉列表数据
				this.getSelsct()
			}
			if (options.title === '查看') this.disabled = true
			if (options.Id) {
				// 如果友id调用工单详情
				this.openForm(options.Id)
			}

		},
		methods: {
			// 时间格式化函数
			getNewTime(time) {
				let newTime = ''
				if (time) {
					newTime = this.$moment(time).format('YYYY-MM-DD')
				}
				return newTime
			},
			// 非空校验
			validEmpty(index, name, tips) {
				return (rule, value, callback) => {
					const data = this.data[index][name]
					if (!data) {
						// this.$message.warning('列表第' + (index + 1) + '行：' + tips)
						callback(tips || '必填')
					} else {
						callback()
					}
				}
			},
			// 关联单号组件回调函数
			ClientSample(event) {
				console.log('关联单号回调', event)
				this.entity.RelationNo = event.DocumentNo;
			},
			// 日期时间选择
			timeClick(type) {
				if (this.disabled) return
				this.dateType = type
				this.isCalendar = true
			},
			// /执行人点击事件
			SalesmanNameClick(SalesmanName) {
				console.log('执行人点击', SalesmanName)
				if (this.disabled) return
				this.$refs.UniPopup.openForm(SalesmanName)
			},
			// form表单清空指定字段校验
			// 清空所有u-form-item组件的内容，本质上是调用了u-form-item组件中的resetField()方法
			resetFields() {
				// 移除表单校验，接受一个参数，类型为 String 或 Array ，只移除传入 name 表单域的值，如果不传入参数，则移除所有
				this.$refs.form.clearValidate(['SalesmanName'])
			},
			// 获取执行人列表数据
			getRealUserName(entity) {
				Base_ManageBase_UserGetDataList({
					PageIndex: 1,
					PageRows: 99999,
					Search: {},
					SortField: "CreateTime",
					SortType: "desc"
				}).then(res => {
					this.selectorObjRealName = res.Data.map(item => {
						return {
							id: item.Id,
							RealName: item.RealName
						}
					})

				});
			},
			//工单类型选择
			SWOTypeOptionsChange(event) {
				console.log('工单类型廁', event)
			},
			// 日期选择calendarChange
			timeChangeClick(event) {
				this.entity[this.dateType] = event.result
				//当前选择日期
				let ApplicationDate = new Date(this.$moment().format("YYYY-MM-DD"));
				// 判断开始日期是否大于当天日期
				if (this.entity.StartTime && this.entity.EndTimeRqstd) {
					// 出发日期
					let StartTime = new Date(this.entity.StartTime);
					// 到达日期
					let EndTimeRqstd = new Date(this.entity.EndTimeRqstd);
					if (StartTime > EndTimeRqstd) {
						this.$errorToast('开始日期不能大于完成日期')
						if (this.DateType === 'DepartureDate') {
							delete this.entity.StartTime
						} else {
							delete this.entity.EndTimeRqstd
						}
						return
					}
				}
			},
			// 创建工单提交
			onSubmit() {
				console.log('提交了', this.entity)

				var that = this
				this.$refs.form.validate().then(res => {
					this.resetFields()
					this.loading = true
					uni.showLoading({
						title: '加载中'
					})
					let newEntity = JSON.parse(JSON.stringify(this.entity))
					// 单独处理工单类型参数
					let SWOType = this.SWOTypeOptions.filter(item => item.value === this.entity.SWOType)[0].text
					newEntity.SWOType = SWOType

					console.log('提交了', newEntity)

					ServiceWorkOrderMainSaveData(newEntity)
						.then(resJson => {
							if (resJson.Success) {
								that.$sucessToast(this.options.title === '编辑' ? '修改成功' : '新建成功')
								setTimeout(function() {
									that.loading = false
									uni.navigateBack()
									uni.hideLoading()
								}, 2500)
							} else {
								that.$errorToast(resJson.Msg);
								setTimeout(function() {
									that.loading = false
									uni.navigateBack()
									uni.hideLoading()
								}, 2500)
							}
						});

				}).catch(err => {
					uni.hideLoading()
					that.loading = false
				})
			},

			// 执行人抄送人回调
			UniPopupConfrim(list) {

				this.entity.SWOAList = list.map(item => ({
					ExecutorId: item.Id,
					ExecutorName: item.RealName
				}));

				this.entity.SalesmanId = this.entity.SWOAList.map(item => {
					return `${item.ExecutorId}-${item.ExecutorName}`;
				});

				let SalesmanName = this.entity.SWOAList.map(
					item => item.ExecutorName
				).join("|");
				this.entity.SalesmanName = this.entity.SWOAList.map(
					item => item.ExecutorName
				).join("|");
				console.log('赋值奥了', this.entity)
				// ************************需要使用此方式插入form表单字段   否则 会出现表单中存在值，确一直校验的情况  ，但是还存在问题，清除后。点击提交就不校验了。后续看怎么优化******************
				this.$refs.form.setValue('SalesmanName', SalesmanName)
				// ************************需要使用此方式插入form表单字段   否则 会出现表单中存在值，确一直校验的情况  ，但是还存在问题，清除后。点击提交就不校验了。后续看怎么优化******************
				this.$forceUpdate()
				this.$refs.UniPopup.close()
			},
			formatDate(date) {
				var time = new Date(date);
				var y = time.getFullYear();

				return `${y}-${date.getMonth() + 1}-${date.getDate()}`;
			},
			formatEndDate(date) {
				var time = new Date(date);
				var y = time.getFullYear();

				return `${y}-${date.getMonth() + 1}-${date.getDate()}`;
			},
			onSWOTypeConfirm(value) {
				this.entity.SWOType = value;
				this.showPicker = false;
			},
			// 获取工单类型下拉数据
			getSelsct(entity) {
				Base_DictionaryMainGetTheDataByDicKey({
						Condition: "DicKey",
						Keyword: "WorkOrderType"
					})
					.then(res => {
						if (res.Data.DictionaryDetailsList.length > 0) {
							this.SWOTypeOptions = res.Data.DictionaryDetailsList.map(item => {
								return {
									value: item.Id,
									text: item.DicName
								}
							});
						}
						// 获取执行人下拉列表数据
						this.getRealUserName(this.entity)
					});
			},
			onConfirm(date) {
				this.showDate = false;
				this.entity.StartTime = this.formatDate(date);
			},
			onEndConfirm(date) {
				this.EndshowDate = false;
				this.entity.EndTimeRqstd = this.formatEndDate(date);
			},
			//选中的产品
			//本条客户的数据
			Client(a) {
				console.log(a);
				this.$set(this.entity, "CustomerName", a.cCusName);

				this.entity.CustomerId = a.Id || a.cCusCode;
			},
			//选择客户
			CustomerChoice() {
				if (this.disabled) return
				this.$refs.myuser.openForm();
			},
			sampleChoice() {
				// 不是查看的条件下弹窗
				if (this.disabled) return
				this.$refs.Sample.openForm();
			},
			getDataList() {
				this.http
					.post("/SampleManagement/SPL_SampleApplyMain/GetTheDataOfAll", {
						SortField: "Id",
						SortType: "desc",
						Search: {
							Condition: "Id",
							Keyword: this.Id
						}
					})
					.then(res => {
						console.log(res);
						if (res.Success) {
							this.entity = res.Data;

							this.$set(
								this.entity,
								"CreateTime",
								this.$moment(this.entity.CreateTime).format('YYYY-MM-DD')
							);
						} else {
							Toast(res.Msg);
						}
					});
			},
			init() {
				this.Id = "";
				this.show = true;
				(this.data = []), (this.entity = {});
			},
			openForm(id) {
				// 获取工单类型下拉列表数据
				this.getSelsct()
				this.entity = {
					SalesmanName: ""
				}

				ServiceWorkOrderMainGetTheDataForDetail({
						id: id
					})
					.then(resJson => {
						this.loading = false;
						// 抄送回显 经办人回显
						this.entity = resJson.Data;
						let newSWOAList = resJson.Data.SWOAList.map(item => {
							return item.ExecutorName
						})
						console.log('获取编辑详情执行人', newSWOAList)

						if (resJson.Data.SWOAList.length > 0 && resJson.Data.SWOAList.length <= 1) {
							// 经办人回显
							if (newSWOAList.length > 0 && newSWOAList.length <= 1) {
								this.entity.SalesmanName = newSWOAList.join('')
							} else {
								this.entity.SalesmanName = newSWOAList.join('|')
							}
						} else {
							this.entity.SalesmanName = newSWOAList.join('|')
						}
						if (this.entity.StartTime) {
							this.$set(
								this.entity,
								"StartTime",
								this.$moment(this.entity.StartTime).format('YYYY-MM-DD')
							);
						}
						if (this.entity.EndTimeRqstd) {
							this.$set(
								this.entity,
								"EndTimeRqstd",
								this.$moment(this.entity.EndTimeRqstd).format('YYYY-MM-DD')
							);
						}
						// 详情工单类型回显
						if (this.entity.SWOType) {
							if (this.SWOTypeOptions.length > 0) {
								let SWOType = this.SWOTypeOptions.filter(item => this.entity.SWOType === item.text)[0]
									.value
								this.entity.SWOType = SWOType
								this.SWOTypeName = this.SWOTypeOptions.filter(item => this.entity.SWOType === item
									.value)[0].text
							}
						}
					});
			}
		}
	};
</script>

<style scoped>
	.Fa {
		display: flex;
		justify-content: left;
	}

	.left {
		margin: 10px 0px 10px 15px;
	}

	.fontstepper {
		margin-left: 15px;
		line-height: 40px;
	}

	.font {
		margin-left: 15px;
		font-size: 18px;
	}

	.aa {
		text-align: right;
	}

	.scrollBar {
		/* height: 550px; */
		height: calc(100vh - 220px);
		/* padding-bottom: 80px; */
		overflow: auto;
	}

	.close {
		position: "absolute";

		right: 0;
		bottom: 0;
		padding: "5px 16px";
		background: "#fff";
		text-align: right;
		z-index: 1;
	}

	/* 适配底部导航栏 */
	.submitButton {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 140px;
		/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
		height: calc(140rpx + constant(safe-area-inset-bottom));
		/* 直接扩展高度，因为padding-bottom是内边距 */
		height: calc(140rpx + env(safe-area-inset-bottom));
		/* 直接扩展高度 */
		background: #fff;
		box-sizing: border-box;
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 iOS<11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS>= 11.2*/
		border-top: 1px solid #e9e9e9;
		padding-top: 5rpx;
		padding-left: 15px;
		padding-right: 15px;
	}

	.mysamplebox {
		width: 95%;

		margin: 0 auto;

		border: 1px solid #ccc;
		/* box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 10px 10px; */

		margin-top: 20px;
		margin-bottom: 10px;
	}

	.confirmBtn {
		/* position: fixed; */
		/* top: 50%; */
		width: 100%;
		height: 44px;
		display: flex;
		justify-content: space-between;
		padding: 0 10px;
		line-height: 2;
		background-color: #fff;
		box-sizing: border-box;
		z-index: 100;
		border-radius: 20px 20px 0 0;
	}

	.comBtn {
		border-radius: 4px;
		margin-top: 5px;
	}
</style>